<?php


namespace App\Http\Controllers;


use App\Helpers\PayPalClient;
use App\Model\Order;
use Carbon\Carbon;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;

class PayPalController extends Controller
{

    public function complete()
    {

        $request = request();

        $order_id = $request->input('out_trade_no');

        $order_sn = $request->input('order_sn');

        $client = PayPalClient::client();

        $response = $client->execute(new OrdersGetRequest($order_id));

        /** @var Order $order */
        $order = Order::where('order_sn', $order_sn)->first();

        if ($order->status !== Order::STATUS_NORMAL) {
            return;
        }

        $orderInfo = $response->result;

        $amount = $orderInfo->purchase_units[0]->amount;

        if ($amount->currency_code !== 'USD') {
            return;
        }

        if ($order->total_price == $amount->value && $orderInfo->status === 'COMPLETED') {
            $order->status = Order::STATUS_PAY;
            $order->pay_at = Carbon::now();
            $order->save();
        }

    }

}
